import { useRef } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Popconfirm, Select, Table } from 'antd';
import dayjs from 'dayjs';
import Saver from 'file-saver';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { filePlusDownloadById } from '@/services/base/kuozhangongnengwenjianguanliPlus';
import {
  proAssayReportDelete,
  proAssayReportPage
} from '@/services/bizApi/shengchanhuayanbaogaojiekou';
import { openUrl } from '@/utils';

import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ProAssayReportEntity;

export const zdOptions = [
  {
    label: '洛碛餐厨污水厂',
    value: '洛碛餐厨污水厂'
  },
  {
    label: '洛碛渗滤液污水处理厂',
    value: '洛碛渗滤液污水处理厂'
  },
  {
    label: '界石污水处理厂',
    value: '界石污水处理厂'
  },
  {
    label: '走马污水处理厂',
    value: '走马污水处理厂'
  },
  {
    label: '黑石子污水处理厂',
    value: '黑石子污水处理厂'
  },
  {
    label: '夏家坝污水处理厂',
    value: '夏家坝污水处理厂'
  }
];

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const [filter] = Filter.useForm();

  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      const res = await proAssayReportPage({
        ...formData,
        ...id,
        deliveryTimeBegin: formData.deliveryDate
          ? dayjs(formData.deliveryDate?.[0]).format('YYYY-MM-DD')
          : undefined,
        deliveryTimeEnd: formData.deliveryDate
          ? dayjs(formData.deliveryDate?.[1]).format('YYYY-MM-DD')
          : undefined,
        reportTimeBegin: formData.reportDate
          ? dayjs(formData.reportDate?.[0]).format('YYYY-MM-DD')
          : undefined,
        reportTimeEnd: formData.reportDate
          ? dayjs(formData.reportDate?.[1]).format('YYYY-MM-DD')
          : undefined,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={() => {
                  edit.current?.open({
                    type: 'add',
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                生成报告
              </Button>
            )}
          </>
        }
      >
        <Filter.Item name="productionSite">
          <Select
            style={{
              width: 180
            }}
            placeholder="站点"
            options={zdOptions}
          />
        </Filter.Item>
        <Filter.Item name="reportDate">
          <DatePicker.RangePicker placeholder={['报告时间', '报告时间']} />
        </Filter.Item>
        <Filter.Item name="deliveryDate">
          <DatePicker.RangePicker placeholder={['送样时间', '送样时间']} />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, row, index) => index + 1
          },
          {
            title: '报告时间',
            dataIndex: 'reportTime',
            render: (text, row) => <div>{dayjs(text).format('YYYY-MM-DD')}</div>
          },
          {
            title: '送样时间',
            dataIndex: 'deliveryTime',
            render: (text, row) => <div>{dayjs(text).format('YYYY-MM-DD')}</div>
          },
          {
            title: '站点',
            dataIndex: 'productionSite'
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              function equDefectAcceptanceSubmit(arg0: { id: string }) {
                throw new Error('Function not implemented.');
              }

              return (
                <Text.Space>
                  {permission.check() && (
                    <Text
                      onClick={async () => {
                        const res = await filePlusDownloadById(
                          {
                            fileId: row?.fileId as unknown as number
                          },
                          {
                            skipErrorHandler: true,
                            responseType: 'blob'
                          }
                        );
                        // 获取文件名
                        const contentDisposition = res.headers['content-disposition'];
                        let filename = '';

                        if (contentDisposition && contentDisposition.indexOf('attachment') !== -1) {
                          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                          const matches = filenameRegex.exec(contentDisposition);
                          if (matches !== null && matches[1]) {
                            filename = decodeURIComponent(matches[1].replace(/['"]/g, ''));
                          }
                        }

                        Saver.saveAs(res?.data, filename);
                      }}
                      type="primary"
                    >
                      报告下载
                    </Text>
                  )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        openUrl(row?.fileUrl as unknown as string);
                      }}
                      type="primary"
                    >
                      报告预览
                    </Text>
                  )}
                  {permission.check() && (
                    <Popconfirm
                      title={`确定删除该条报告吗？`}
                      onConfirm={async () => {
                        const res = await proAssayReportDelete({
                          id: row.id as unknown as string
                        });

                        store.app?.message.success('删除成功');
                        table.refresh();
                      }}
                    >
                      <Text>删除</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
    </>
  );
};

export default Page;
